package com.weilive.core.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public final class HttpUtils {
	public static int TIMEOUT = 10 * 1000;

	private HttpUtils() {
	}

	private static class TrustAnyTrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAnyHostnameVerifier implements HostnameVerifier {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	// ***************************************HTTP***************************************
	/**
	 * 发送HTTP GET请求并获取结果
	 * 
	 * @param goUrl
	 * @return
	 * @throws Exception
	 */
	public static String HttpGetGo(String goUrl) {
		return HttpGo(goUrl, "GET", null);
	}

	/**
	 * 发送HTTP POST请求并返回结果
	 * 
	 * @param goURL
	 * @param body
	 * @return
	 * @throws Exception
	 */
	public static String HttpPostGo(String goURL, String body) {
		return HttpGo(goURL, "POST", body);
	}

	private static String HttpGo(String goURL, String method, String body) {
		HttpURLConnection urlConnection = null;
		try {
			urlConnection = (HttpURLConnection) new URL(goURL).openConnection();
			urlConnection.setRequestMethod(method);
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setConnectTimeout(TIMEOUT);
			urlConnection.setReadTimeout(TIMEOUT);
			// urlConnection.setRequestProperty("Cookie", cookie);
			if (body != null) {
				urlConnection.getOutputStream().write(body.getBytes());
				urlConnection.getOutputStream().flush();
				urlConnection.getOutputStream().close();
			}

			InputStream in = urlConnection.getInputStream();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
			StringBuffer temp = new StringBuffer();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				temp.append(line);
			}
			bufferedReader.close();

			// String cookie = urlConnection.getHeaderField("Set-Cookie");
			// System.out.println(CookieUtils.getCookie(cookie));

			String ecod = urlConnection.getContentEncoding();
			if (ecod == null) {
				return temp.toString();
			} else {
				return new String(temp.toString().getBytes(), ecod);
			}
		} catch (Exception e) {
			return null;
		} finally {
			urlConnection.disconnect();
		}
	}

	// ***************************************HTTP***************************************
	// ***************************************HTTPS***************************************
	/**
	 * 发送HTTPS GET请求并返回结果
	 * 
	 * @param goURL
	 * @return
	 * @throws Exception
	 */
	public static String HttpsGetGo(String goURL) {
		return HttpsGo(goURL, "GET", null);
	}

	/**
	 * 发送HTTPS POST请求并返回结果
	 * 
	 * @param goURL
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public static String HttpsPostGo(String goURL, String body) {
		return HttpsGo(goURL, "POST", body);
	}

	private static String HttpsGo(String goURL, String method, String body) {
		HttpsURLConnection urlConnection = null;
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
			URL console = new URL(goURL);
			urlConnection = (HttpsURLConnection) console.openConnection();
			urlConnection.setSSLSocketFactory(sc.getSocketFactory());
			urlConnection.setHostnameVerifier(new TrustAnyHostnameVerifier());
			urlConnection.setRequestMethod(method);
			urlConnection.setRequestProperty("content-type", "text/json");
			urlConnection.setRequestProperty("Proxy-Connection", "Keep-Alive");
			// urlConnection.setRequestProperty("Cookie",
			// "SESSID=f1mr4tccpdk7r68b5cupk9lsf6; path=/;
			// domain=api.weilive.cc");
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			urlConnection.setConnectTimeout(TIMEOUT);
			urlConnection.setReadTimeout(TIMEOUT);
			urlConnection.connect();

			if (body != null) {
				urlConnection.getOutputStream().write(body.getBytes("UTF-8"));
				urlConnection.getOutputStream().flush();
				urlConnection.getOutputStream().close();
			}

			InputStream in = urlConnection.getInputStream();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
			StringBuffer temp = new StringBuffer();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				temp.append(line);
			}
			bufferedReader.close();

			String cookie = urlConnection.getHeaderField("Set-Cookie");
			System.out.println(cookie);

			String ecod = urlConnection.getContentEncoding();
			if (ecod == null) {
				return temp.toString();
			} else {
				return new String(temp.toString().getBytes(), ecod);
			}
		} catch (Exception e) {
			return null;
		} finally {
			urlConnection.disconnect();
		}
	}

	// ***************************************HTTPS***************************************
	public static Map<String, String> getParamsMap(String s) throws UnsupportedEncodingException {
		Map<String, String> parms = new HashMap<String, String>();
		if (s == null || s.length() == 0) {
			return parms;
		}

		String[] strs = s.split("&");
		for (String str : strs) {
			int index = str.indexOf("=");
			String k = str.substring(0, index);
			String v = str.substring(index + 1, str.length());

			// v = URLDecoder.decode(v, "UTF-8");
			parms.put(k, v);
		}
		return parms;
	}

	// public static String postRequest(String uri, String body) {
	// String output;
	// CloseableHttpClient httpClient = HttpClients.createDefault();
	// try {
	// HttpPost postRequest = new HttpPost(uri);
	// postRequest.setHeader("Content-Type", "application/json;charset=utf-8");
	// StringEntity input = new StringEntity(body, "utf-8");
	// postRequest.setEntity(input);
	//
	// HttpResponse response = httpClient.execute(postRequest);
	//
	// if (response.getStatusLine().getStatusCode() != 200) {
	// throw new RuntimeException("POST调用异常 : " +
	// response.getStatusLine().getStatusCode());
	// }
	// output = EntityUtils.toString(response.getEntity(), "utf-8");
	//
	// } catch (IOException e) {
	// throw new RuntimeException("POST调用异常", e);
	// } finally {
	// try {
	// httpClient.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }
	// return output;
	// }
}
